using System;
using Facebook.Entity;
using Facebook.Components;
using System.Data;
using System.Data.SqlClient;

namespace FacebookUtilities
{
    public class FacebookUtil
    {
        private FacebookService _service;

        public FacebookUtil()
        {
            _service = new FacebookService();
            _service.IsDesktopApplication = true;
            _service.ApplicationKey = "5d0779e91063c061f7728d9d153bf57a";
            _service.Secret = "8616ddee42a3cf26b2f6b05b78096571";
            _service.ConnectToFacebook();
        }

        public String GetGreetingMsg()
        {
            return "Hello Facebook!";
        }

        public string GetUser()
        {
            return _service.GetUserInfoXml(_service.GetUserInfo().UserId);
        }
        
        public string GetAlerts(string sqlservername)
        {
            // Get my information.
            User me = _service.GetUserInfo();
            Notifications alerts = _service.GetNotifications();

            SqlConnection mySqlConnection = null;
            SqlDataAdapter mySqlDataAdapter = null;
            DataSet dsAlerts = null;
            string connString = "Data Source=" + sqlservername + ";Persist Security Info=True;Integrated Security=SSPI;Initial Catalog=FBDatabase";

            bool msgReceived = false;
            bool pokeReceived = false;
            bool shareReceived = false;
            bool friendreqReceived = false;
            bool groupinvtReceived = false;
            bool eventinvtReceived = false;

            string xmlReturn = null;
        
            try
            {
                mySqlConnection = new SqlConnection(connString);
                mySqlDataAdapter = new SqlDataAdapter("SELECT * from FaceBookAlerts", mySqlConnection);

                // Create command builder. This line automatically generates the update commands 
                // for you, so you don't have to provide or create your own.
                SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(mySqlDataAdapter);

                dsAlerts = new DataSet();
                mySqlDataAdapter.Fill(dsAlerts, "FaceBookAlerts");

                // Create a new dataview instance on the Customers table that was just created
                DataView myDataView = new DataView(dsAlerts.Tables["FaceBookAlerts"]);
                if (myDataView.Count > 0)
                {
                    // Sort the view based on the FirstName column
                    myDataView.Sort = "FaceBookID";
                    // Filter the dataview to only show customers with the CustomerID of ALFKI
                    myDataView.RowFilter = "FaceBookID= '" + me.UserId + "'";
                }

                if (myDataView.Count > 0)
                {
                    if (Convert.ToInt32(alerts.MostRecentMessageId) != Convert.ToInt32(myDataView[0]["mostrecentmsg"]) 
                        && alerts.UnreadMessageCount > Convert.ToInt32(myDataView[0]["unreadmsg"])) msgReceived = true;
	                if (Convert.ToInt32(alerts.MostRecentPokeId) != Convert.ToInt32(myDataView[0]["mostrecentpoke"]) 
                        && alerts.UnreadPokeCount > Convert.ToInt32(myDataView[0]["unreadpoke"])) pokeReceived = true;
	                if (Convert.ToInt32(alerts.MostRecentShareId) != Convert.ToInt32(myDataView[0]["mostrecentshare"]) 
                        && alerts.UnreadShareCount > Convert.ToInt32(myDataView[0]["unreadshare"])) shareReceived = true;
                    if (alerts.FriendRequests.Count > Convert.ToInt32(myDataView[0]["friendrequests"])) friendreqReceived = true;
                    if (alerts.GroupInvites.Count > Convert.ToInt32(myDataView[0]["groupinvites"])) groupinvtReceived = true;
                    if (alerts.EventInvites.Count > Convert.ToInt32(myDataView[0]["eventinvites"])) eventinvtReceived = true;
            	    
                    myDataView[0]["FaceBookID"] = Convert.ToInt32(me.UserId);
                    myDataView[0]["Name"] = me.Name;
                    myDataView[0]["unreadmsg"] = alerts.UnreadMessageCount;
                    myDataView[0]["mostrecentmsg"] = Convert.ToInt32(alerts.MostRecentMessageId);
                    myDataView[0]["unreadpoke"] = alerts.UnreadPokeCount;
                    myDataView[0]["mostrecentpoke"] = Convert.ToInt32(alerts.MostRecentPokeId);
                    myDataView[0]["unreadshare"] = alerts.UnreadShareCount;
                    myDataView[0]["mostrecentshare"] = Convert.ToInt32(alerts.MostRecentShareId);
                    myDataView[0]["friendrequests"] = alerts.FriendRequests.Count;
                    myDataView[0]["groupinvites"] = alerts.GroupInvites.Count;
                    myDataView[0]["eventinvites"] = alerts.EventInvites.Count;
	                if (msgReceived) myDataView[0]["mostrecentmsgtime"] = DateTime.Now;
                    if (pokeReceived) myDataView[0]["mostrecentpoketime"] = DateTime.Now;
                    if (shareReceived) myDataView[0]["mostrecentsharetime"] = DateTime.Now;
                    if (friendreqReceived) myDataView[0]["friendrequeststime"] = DateTime.Now;
                    if (groupinvtReceived) myDataView[0]["groupinvitestime"] = DateTime.Now;
                    if (eventinvtReceived) myDataView[0]["eventinvitestime"] = DateTime.Now;
                }
                else
                {
                    DataRow myDataRow = dsAlerts.Tables["FaceBookAlerts"].NewRow();
                    myDataRow["FaceBookID"] = Convert.ToInt32(me.UserId);
                    myDataRow["Name"] = me.Name;
                    myDataRow["unreadmsg"] = alerts.UnreadMessageCount;
                    myDataRow["mostrecentmsg"] = Convert.ToInt32(alerts.MostRecentMessageId);
                    myDataRow["unreadpoke"] = alerts.UnreadPokeCount;
                    myDataRow["mostrecentpoke"] = Convert.ToInt32(alerts.MostRecentPokeId);
                    myDataRow["unreadshare"] = alerts.UnreadShareCount;
                    myDataRow["mostrecentshare"] = Convert.ToInt32(alerts.MostRecentShareId);
                    myDataRow["friendrequests"] = alerts.FriendRequests.Count;
                    myDataRow["groupinvites"] = alerts.GroupInvites.Count;
                    myDataRow["eventinvites"] = alerts.EventInvites.Count;
                    dsAlerts.Tables["FaceBookAlerts"].Rows.Add(myDataRow);
                }

                // Update Database with SqlDataAdapter
                mySqlDataAdapter.Update(dsAlerts, "FaceBookAlerts");

                xmlReturn = "<Notifications><Notification " +
                   "FaceBookID=\"" + me.UserId.ToString() + "\" " +
                   "Name=\"" + me.Name + "\" " +
                   "msgCount=\"" + alerts.UnreadMessageCount.ToString() + "\" " +
                   "pokeCount=\"" + alerts.UnreadPokeCount.ToString() + "\" " +
                   "shareCount=\"" + alerts.UnreadShareCount.ToString() + "\" " +
                   "friendinvitationCount=\"" + alerts.FriendRequests.Count.ToString() + "\" " +
                   "groupinvitationCount=\"" + alerts.GroupInvites.Count.ToString() + "\" " +
                   "eventinvitationCount=\"" + alerts.EventInvites.Count.ToString() + "\" " +
                   "mostrecentmsgtime=\"" + myDataView[0]["mostrecentmsgtime"].ToString() + "\" " +
                   "mostrecentpoketime=\"" + myDataView[0]["mostrecentpoketime"].ToString() + "\" " +
                   "mostrecentsharetime=\"" + myDataView[0]["mostrecentsharetime"].ToString() + "\" " +
                   "friendrequeststime=\"" + myDataView[0]["friendrequeststime"].ToString() + "\" " +
                   "groupinvitestime=\"" + myDataView[0]["groupinvitestime"].ToString() + "\" " +
                   "eventinvitestime=\"" + myDataView[0]["eventinvitestime"].ToString() + "\" " +
                   "msgReceived=\"" + msgReceived + "\" " +
                   "pokeReceived=\"" + pokeReceived + "\" " +
                   "shareReceived=\"" + shareReceived + "\" " +
                   "friendreqReceived=\"" + friendreqReceived + "\" " +
                   "groupinvtReceived=\"" + groupinvtReceived + "\" " +
                   "eventinvtReceived=\"" + eventinvtReceived + "\" " +
                   "/></Notifications>";
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                mySqlConnection.Close();
            }

            return xmlReturn;
        }
    }
}